package com.zh.eventdispatcher;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zh.eventdispatch.activity.ActivityEventObserver;
import com.zh.eventdispatch.activity.ActivityEventOwner;
import com.zh.eventdispatch.activity.EventDispatcherFragment;
import com.zh.eventdispatcher.widget.FloatView;
import com.zh.eventdispatcher.widget.ToolBoxView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.SelectionCreator;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * @author wally
 * @date 2021/06/19
 */
public class LiveFragment extends EventDispatcherFragment {
    private static final String TAG = LiveFragment.class.getSimpleName();

    private final int REQUEST_CODE_CHOOSE_PHOTO = 1;

    private ImageView vChooseImage;

    RxPermissions mRxPermissions;
    private Disposable mDisposable;

    public static LiveFragment newInstance() {
        return new LiveFragment();
    }

    @Override
    public void onAttach(@NonNull Activity activity) {
        super.onAttach(activity);
        mRxPermissions = new RxPermissions(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_live, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        FloatView floatView = view.findViewById(R.id.float_view);
        ToolBoxView toolBoxView = view.findViewById(R.id.tool_box);
        vChooseImage = view.findViewById(R.id.choose_image);
        Button printObservers = view.findViewById(R.id.print_observers);

        view.findViewById(R.id.toggle_float).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatView.toggle();
            }
        });
        view.findViewById(R.id.toggle_tool_box).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toolBoxView.toggle();
            }
        });
        toolBoxView.bindCallback(new ToolBoxView.Callback() {
            @Override
            public void onTakePhoto() {
                takeImage(true);
            }

            @Override
            public void onTakeGallery() {
                takeImage(false);
            }
        });
        printObservers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityEventOwner eventOwner = getActivityEventOwner();
                if (eventOwner != null) {
                    List<ActivityEventObserver> observers = eventOwner.getEventDispatcher()
                            .getEventObservers();
                    Log.d(TAG, observers.toString());
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    /**
     * 选择图片
     *
     * @param isCamera 是否通过拍照选择
     */
    private void takeImage(boolean isCamera) {
        mDisposable = mRxPermissions.request(Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean result) throws Exception {
                if (getContext() == null) {
                    return;
                }
                if (result) {
                    SelectionCreator creator = Matisse.from(getActivity())
                            .choose(MimeType.ofImage(), false)
                            .captureStrategy(new CaptureStrategy(true, "com.zh.eventdispatcher.fileprovider"))
                            .theme(R.style.Matisse_Dracula)
                            .countable(true)
                            .maxSelectable(1);
                    //使用相机
                    if (isCamera) {
                        creator.capture(true);
                    }
                    creator.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .thumbnailScale(0.87f)
                            .imageEngine(new GlideLoadEngine())
                            .forResult(REQUEST_CODE_CHOOSE_PHOTO);
                } else {
                    Toast.makeText(getContext().getApplicationContext(), "没有允许权限", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public boolean onSupportActivityResult(int requestCode, int resultCode, Intent data) {
        if (getActivity() == null) {
            return super.onSupportActivityResult(requestCode, resultCode, data);
        }
        if (requestCode == REQUEST_CODE_CHOOSE_PHOTO && resultCode == Activity.RESULT_OK) {
            //获取图片路径
            List<Uri> paths = Matisse.obtainResult(data);
            for (Uri uri : paths) {
                Glide.with(getActivity()).load(uri).into(vChooseImage);
            }
            return true;
        }
        return super.onSupportActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onSupportBackPressed() {
        super.onSupportBackPressed();
        FragmentActivity activity = getActivity();
        if (activity == null || activity.isFinishing()) {
            return false;
        }
        new AlertDialog.Builder(activity)
                .setMessage("是否退出直播间？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        activity.finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
        return true;
    }
}